import 'package:family_expense/features/journey/models/journey.dart';
import 'package:family_expense/features/journey/models/journey_income_expense_detail.dart';
import 'package:family_expense/features/journey/services/journey_income_expense_detail_service.dart';
import 'package:family_expense/features/journey/services/journey_service.dart';
import 'package:family_expense/features/journey/widgets/edit_journey.dart';
import 'package:family_expense/features/journey/widgets/journey_income_expense_detail_shared.dart';
import 'package:family_expense/features/journey/widgets/journey_income_expense_detail_view.dart';
import 'package:family_expense/features/journey/widgets/journey_income_expense_list.dart';
import 'package:family_expense/features/journey/widgets/region_shared.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class JourneyList extends StatefulWidget {
  const JourneyList({super.key});

  @override
  State<JourneyList> createState() => _JourneyListState();
}

class _JourneyListState extends State<JourneyList> {
  final int _pageSize = GeneralConfig.listViewPageSize;
  final JourneyService _journeyService = JourneyService();

  final JourneyIncomeExpenseDetailService _incomeExpenseDetailService =
      JourneyIncomeExpenseDetailService();

  late String _keyword;

  // In order to refresh the list after item changes. Including updated, added or removed.
  late PagingListViewLoadController _loadController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: _buildAppBar(), body: _buildBody());
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: const Text('旅程列表'),
      actions: <Widget>[
        FutureBuilder<User?>(
          future: AuthStateService.instance.currentUser,
          builder: (context, userSnapshot) => IconButton(
            icon: const Icon(Icons.more_horiz),
            onPressed: () {
              showModalBottomSheet(
                context: context,
                builder: (context) {
                  return getSelectionBottomSheetContent([
                    if (userSnapshot.data?.isViewerOnly == false)
                      ListTile(
                        leading: const Icon(Icons.add),
                        title: const Text('添加旅程'),
                        onTap: () {
                          // Closes opened bottom sheet.
                          NavigatorHelper.pop(context);

                          _gotoAddView();
                        },
                      ),
                    ListTile(
                      leading: const Icon(Icons.search),
                      title: const Text('搜索收支'),
                      onTap: () {
                        // Closes opened bottom sheet.
                        NavigatorHelper.pop(context);

                        _openSearch();
                      },
                    ),
                  ], isHoriz: false);
                },
              );
            },
          ),
        ),
      ],
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return PagingListView(
      padding: const EdgeInsets.only(top: 10.0),
      pageSize: _pageSize,
      getLoadController: (loadController) => _loadController = loadController,
      retrieveData: (pageIndex) =>
          _journeyService.queryListByAccountGroup(_pageSize, pageIndex!),
      itemBuilder: (context, entry, index) => _buildListTile(entry),
    );
  }

  /// Builds list tile to show journey info.
  Widget _buildListTile(Journey journey) {
    return SimpleDetailListTile(
      title: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          RegionFlag(journey.region!),
          const SizedBox(width: 8.0),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(journey.region!.title!),
              Text(
                '${journey.startDate.formatDate(DatePatterns.longDate)} 至 ${journey.endDate.formatDate(DatePatterns.longDate)}',
                style: Theme.of(context).textTheme.bodySmall,
              ),
            ],
          ),
        ],
      ),
      onTap: () async {
        final dataUpdated = await NavigatorHelper.push<bool>(
          context,
          JourneyIncomeExpenseList(journey),
        );

        if (dataUpdated == true) {
          _loadController.reset();
        }
      },
    );
  }

  /// Builds list tile to show journey income/expense search result.
  Widget _buildJourneyIncomeExpenseSearchResultListTile(
    JourneyIncomeExpenseDetail incomeExpenseDetail,
  ) {
    return JourneyIncomeExpenseDetailListTile(
      incomeExpenseDetail,
      () {
        NavigatorHelper.push<bool>(
          context,
          JourneyIncomeExpenseDetailView(
            id: incomeExpenseDetail.id!,
            journey: incomeExpenseDetail.journey!,
          ),
        );
      },
      region: incomeExpenseDetail.journey!.region!.title,
      keywords: _keyword.split(' '),
    );
  }

  Future<void> _gotoAddView() async {
    final result = await NavigatorHelper.push<EditJourneyResult>(
      context,
      const EditJourney(),
    );

    if (result?.dataUpdated == true) {
      _loadController.reset();
    }
  }

  Future<void> _openSearch() async {
    showSearch<dynamic>(
      context: context,
      delegate: GeneralSearchDelegate(
        (keyword) {
          _keyword = keyword;

          return _incomeExpenseDetailService.queryListByJourney(
            pageSize: _pageSize,
            pageIndex: 0,
            keyword: keyword,
          );
        },
        buildSuggestionItem: (entry) =>
            _buildJourneyIncomeExpenseSearchResultListTile(entry),
      ),
    );
  }
}
